package com.aliyun.messagemgt.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhangyajie
 * @date 2019/8/21
 */
public class FileUtils {

    /**
     * 文件夹不存在就创建
     * @param file
     * @return
     */
    public static boolean isdirctor(String file){
        if(!new File(file).exists())   {
            new File(file).mkdirs();
        }
        return true;
    }

    /**
     * 创建文件
     * @param filePath
     * @return
     */
    public static boolean createFile(String filePath){
        File docxFile = new File(filePath);
        if (!docxFile.exists()) {
            try {
                docxFile.createNewFile();
            } catch (IOException e) {
                return false;
            }
        }
        return true;
    }

    /**
     * 删除文件夹里面的所有文件
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                //先删除文件夹里面的文件
                delAllFile(path + "/" + tempList[i]);
                //再删除空文件夹
                delFolder(path + "/" + tempList[i]);
                flag = true;
            }
        }
        return flag;
    }
    /**
     * 删除文件
     * @param filePath
     * @return
     */
    public static boolean delFile(String filePath) {
    	boolean flag = false;
    	File file = new File(filePath);
    	if (!file.exists()) {
    		return flag;
    	}

    	if (file.isFile()) {
    		file.delete();
    		flag = true;

    	}
    	return flag;
    }

    /**
     * 删除文件夹
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            //删除完里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        output.close();
        return output.toByteArray();
    }
}